/*
 * ============================================================================
 *
 *       Filename:  bin_ascii.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2013年05月06日 09时51分59秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>

void bin_echo(char data)
{
	int test = 1;
	int i;
	for(i = 7; i >= 0; i--){
		if(data & (test << i))
			printf("1");
		else
			printf("0");
	}
	printf("\n");
}

void decode(int file)
{
	char buf[8] = {0};
	unsigned char tmp = 0;
	int i;

	mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
	int output = open("outputfile",O_CREAT|O_APPEND|O_RDWR|O_TRUNC,mode);

	while(read(file,&buf,8) == 8){
		for(i = 0; i < 8; i++)
			tmp |= (buf[i] - '0') << (7 - i);

		bin_echo(tmp);
		write(output,&tmp,1);
		tmp = 0;
	}
}

int main(int argc, char *argv[])
{
	if(argc < 2){
		fprintf(stderr,"No input file\n");
		return -1;
	}

	int file;
	if((file = open(argv[1],O_RDONLY)) == -1){
		perror(NULL);
		return -1;
	}

	off_t len = lseek(file,0,SEEK_END);
	if((len & 7) != 0)
		fprintf(stderr,"WARNING: Is not 8 alignment: %d\n",len);
	lseek(file,0,SEEK_SET);

	decode(file);
	return 0;
}
